<template>
  <div class="page-container">
    <div class="header-banner"><h2>物流跟踪</h2></div>

    <div class="main-content">
      <!-- 左侧列表 -->
      <div class="delivery-list">
        <el-card shadow="hover" class="list-card">
          <h3 class="card-title">物流列表</h3>
          <el-table
            :data="deliveryList"
            highlight-current-row
            @row-click="handleRowClick"
            :row-class-name="rowClass"
          >
            <el-table-column prop="deliverySn"  label="物流单号"  width="180"/>
            <el-table-column label="配送方式"  width="100">
              <template #default="{row}">{{ row.deliveryType===1 ? '快递' : '自提' }}</template>
            </el-table-column>
            <el-table-column label="状态" width="110">
              <template #default="{row}">{{ statusText(row) }}</template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>

      <!-- 右侧地图或提示 -->
      <div class="delivery-map">
        <el-card shadow="hover" class="map-card">
          <h3 class="card-title">{{ selected ? '运输路线' : '提示' }}</h3>

          <!-- 未选择 -->
          <div v-if="!selected" class="map-placeholder">请选择一条物流记录</div>

          <!-- 自提 -->
          <div v-else-if="selected.deliveryType !== 1" class="map-placeholder">
            <p>门店自提订单不展示路线</p>
            <el-button
              v-if="selected.status===1"
              size="small"
              type="primary"
              @click="confirm"
            >我已取件</el-button>
          </div>

          <!-- 快递：地图 -->
          <div v-show="selected && selected.deliveryType === 1">
            <div id="map-container" style="height:360px;"></div>
            <el-button
              v-if="selected?.status === 1"
              size="small"
              type="primary"
              class="mt-2"
              @click="confirm"
            >确认收货</el-button>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { getDeliveryList, getDeliveryDetail, confirmDelivery } from '@/api/delivery'
import { deepParse } from '@/utils/deepParse';

/* ---------- 列表 & 当前选择 ---------- */
const deliveryList = ref([])
const selected     = ref(null)

/* ---------- 状态文本 ---------- */
const statusText = row => (
  row.deliveryType === 1
    ? ['待发货', '运输中', '已签收'][row.status]
    : ['待备货', '待自提', '已取件'][row.status]
)

/* ---------- 地图初始化 ---------- */
const JS_KEY = import.meta.env.VITE_AMAP_JS_KEY
const JS_SEC = import.meta.env.VITE_AMAP_JS_SECURITY

let map, driving, geocoder

const loadAmap = () => new Promise((ok, fail) => {
  if (window.AMap) return ok()

  if (JS_SEC) {
    window._AMapSecurityConfig = { securityJsCode: JS_SEC }
  }

  const s = document.createElement('script')
  s.src = `https://webapi.amap.com/maps?v=2.0&key=${JS_KEY}&plugin=AMap.Driving,AMap.Geocoder`
  s.onload = ok
  s.onerror = () => fail('高德 JS SDK 加载失败')
  document.head.appendChild(s)
})

const initMap = () => {
  map = new AMap.Map('map-container', { zoom: 12 })
  driving  = new AMap.Driving({ map })
  geocoder = new AMap.Geocoder({ city: '全国' })
}

/* ---------- 加载列表 ---------- */
const fetchList = async () => {
  const res = await getDeliveryList({ page: 1, size: 100 });
  if (res.data.code !== '200') {
    ElMessage.error(res.data.message || '获取列表失败');
    return;
  }
  
  let list = Array.isArray(res.data.data)
    ? res.data.data
    : res.data.data.records;

  list = list.map(r => ({
    ...r,
    senderInfo: deepParse(r.senderInfo),
    receiverInfo: deepParse(r.receiverInfo)
  }));

  list = list.filter(r => r.deliveryType === 1 && r.deliverySn)

  deliveryList.value = list;
};

const handleRowClick = async row => {
  const { data } = await getDeliveryDetail(row.deliverySn);
  selected.value = data.data;

  selected.value.senderInfo   = deepParse(selected.value.senderInfo);
  selected.value.receiverInfo = deepParse(selected.value.receiverInfo);

  if (selected.value.deliveryType !== 1) return;
  await nextTick();
  if (!map) initMap();
  map.resize();
  await drawRoute(
    selected.value.senderInfo.address,
    selected.value.receiverInfo.address
  );
};


/* ---------- 画路线 ---------- */
const geocode = addr => new Promise((res, rej) => {
  geocoder.getLocation(addr, (st, r) => {
    if (st === 'complete' && r.geocodes.length) res(r.geocodes[0].location)
    else rej(`地址解析失败：${addr}`)
  })
})

const drawRoute = async (startAddr, endAddr) => {
  try {
    map.clearMap()
    const [start, end] = await Promise.all([geocode(startAddr), geocode(endAddr)])

    driving.search(start, end, (status, result) => {
      if (status !== 'complete') {
        ElMessage.error('路线规划失败')
        return
      }
      map.setFitView()   // 🆕 自动适配视野
    })
  } catch (e) {
    ElMessage.error(e)
  }
}


/* ---------- 确认收货 / 取件 ---------- */
const confirm = async () => {
  await confirmDelivery(selected.value.deliverySn)
  ElMessage.success('操作成功')
  await fetchList()
  selected.value.status = 2
}

/* ---------- 行高亮 ---------- */
const rowClass = ({ row }) => (row === selected.value ? 'selected-row' : '')

/* ---------- INIT ---------- */
onMounted(async () => {
  await fetchList()
  await nextTick()
  await loadAmap()
  initMap()
})
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background: #f8f9fc;
  padding: 16px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.header-banner {
  text-align: center;
  padding: 12px 0;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;

  h2 {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }
}

.main-content {
  flex: 1;
  display: flex;
  gap: 16px;

  @media (max-width: 768px) {
    flex-direction: column;
  }
}

.delivery-list {
  width: 400px;
  flex-shrink: 0;
}

.delivery-map {
  flex: 1;
  min-width: 0;
}

.list-card,
.map-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background: #ffffff;
  transition: transform 0.2s ease;
  height: 86%;

  &:hover {
    transform: translateY(-2px);
  }
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 12px;
  text-align: left;
}

.delivery-table {
  font-size: 14px;
  cursor: pointer;

  :deep(.el-table__header th) {
    font-size: 14px;
    background: #fafafa;
    color: #606266;
  }

  :deep(.el-table__cell) {
    padding: 8px;
  }

  :deep(.selected-row) {
    background: #e6f1ff;
  }

  :deep(.el-table__row) {
    cursor: pointer;
    
    &:hover {
      background-color: #f5f7fa;
    }
  }

  .status-0 { color: #909399; }
  .status-1 { color: #409eff; }
  .status-2 { color: #67c23a; }
  .status-3 { color: #e6a23c; }
}

.map-placeholder {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #606266;
}

#map-container {
  border-radius: 8px;
  overflow: hidden;
}
</style>